package cn.wit.summit.chwan.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.CommentAllListFragmentAdapter;
import cn.wit.summit.chwan.models.dto.CommentAlllistIntentData;
import cn.wit.summit.chwan.models.dto.CommentBaseBean;
import cn.wit.summit.chwan.models.event.DeleteOrModifyCommentEvent;
import cn.wit.summit.chwan.models.request.AddPraiseRequest;
import cn.wit.summit.chwan.models.request.GetCommentTokenRequest;
import cn.wit.summit.chwan.models.request.GetGameCommentRequest;
import cn.wit.summit.chwan.models.response.AddPraiseResponse;
import cn.wit.summit.chwan.models.response.CommentAllListResponse;
import cn.wit.summit.chwan.models.response.GetCommentTokenResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.base.BaseActivity;
import cn.wit.summit.chwan.utils.AESUtils;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StringToUnicodeUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/4/22.
 */

public class CommentAllListV2Activity extends BaseActivity implements CommentAllListFragmentAdapter.Listener {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private TextView mBarRightTx;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    private String comentToken = "-1";
    private int uId;
    private String uToken;

    private String commentId;
    private String commentContent;
    private float commentStars;
    private String gameId;
    private String packageName;
    private String commentScoreSwitch;//星星开关 1：开，0：关
    private int bespeakSwitch;//是否是预约游戏 1：开，0：关
    private int sgcSwitch;//游戏启动次数 1：开，0：关
    private String gameType;
    private int gameIsStart;

    private CommentAllListFragmentAdapter mAdapter;
    private List<CommentAllListFragmentAdapter.ViewBean> dataSet = new ArrayList<>();

    private int pn = 1;
    private int pc = 10;

    private CommentBaseBean selfComment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        actionBarStyle = ACTION_BAR_NORMAL;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment_all_list_v2);
        ButterKnife.bind(this);

        setBarTitleTx(R.string.comment_all_title_str);

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofit = retrofitManager.getCommentRetrofit();
        api = retrofit.create(ApiUtil.class);

        initData();
        initView();
        initListView();
    }

    private void initView() {
        mBarRightTx = setBarRightTx(getResources().getString(R.string.comment_all_right_str));
        mBarRightTx.setBackgroundResource(R.drawable.selector_commit_bg);
        mBarRightTx.setTextColor(Color.parseColor("#6A99FF"));
        mBarRightTx.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.wdp28));
        mBarRightTx.setEnabled(true);
        mBarRightTx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AccountUtil.getInstance().getUidNotToLogin(mContext) == 0) return;
                Intent intent = new Intent(mContext, CommentCreatActivity.class);
                if (selfComment != null) {
                    intent.putExtra("isEdit", true);
                    intent.putExtra("commentId", selfComment.getId());
                    intent.putExtra("phoneModel", selfComment.getMobile_phone_model());
                    intent.putExtra("commentContent", selfComment.getContent());
                }
                intent.putExtra("gameId", gameId);
                startActivity(intent);
            }
        });
    }

    private void initListView() {
        mAdapter = new CommentAllListFragmentAdapter(mContext, uId, dataSet, this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mAdapter);
        recyclerView.setFocusable(false);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                pn = 1;
                getData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                getData();
            }
        });

//        showSkeleton();
        pn = 1;
        getData();
    }

    private void initData() {

        CommentAlllistIntentData intentData = (CommentAlllistIntentData) getIntent().getSerializableExtra("intentData");

        commentId = intentData.getCommentId();
        commentContent = intentData.getCommentContent();
        gameId = intentData.getGameId();
        gameType = intentData.getGameType();
        packageName = intentData.getPackageName();
        commentScoreSwitch = intentData.getCommentScoreSwitch();
        commentStars = intentData.getCommentStars();
        gameIsStart = intentData.getGameIsStart();
        bespeakSwitch = intentData.getBespeakSwitch();
        sgcSwitch =intentData.getSgcSwitch();

        if (AccountUtil.getInstance().getAccountData()!=null) {
            uId = AccountUtil.getInstance().getUid();
            uToken = AccountUtil.getInstance().getToken();
        }
    }

    private void getData() {
        comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
        if (StringUtils.isEmpty(comentToken) || comentToken.equals("-1")) {
            getCommentToken(null, 0, 0, 3);
            return;
        }
        uId = AccountUtil.getInstance().getUid();
        uToken = AccountUtil.getInstance().getToken();

        GetGameCommentRequest commentRequest = retrofitManager.getGameCommentsRequest(comentToken, gameId, uId, pn, pc);
        api.getGameComments(commentRequest).enqueue(new MyCallback<ResponseBase<CommentAllListResponse>>() {
            @Override
            public void onSuccess(ResponseBase<CommentAllListResponse> model) {
                showMain(model.getData_info());
            }

            @Override
            public void onFailure(int code, String msg) {
                showToast(msg);
                hideSkeleton();
                refreshLayout.finishRefresh(false);
                refreshLayout.finishLoadMore(false);
                refreshLayout.finishRefresh();
            }
        });
    }

    private void showMain(CommentAllListResponse commentBeans) {
        if (commentBeans==null) {
            if (pn==1) {
                CommentAllListFragmentAdapter.ViewBean viewBean = new CommentAllListFragmentAdapter.ViewBean(CommentAllListFragmentAdapter.ViewType.EMPTY, null);
                dataSet.add(viewBean);
                mAdapter.notifyDataSetChanged();
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
            return;
        }
        if (pn == 1) {
            dataSet.clear();
        }

        List<CommentBaseBean> commentBaseBeans = new ArrayList<>();

        List<CommentBaseBean> hotComment = commentBeans.getHot_comment();
        if (hotComment!=null && hotComment.size()>0) {
            CommentBaseBean bean = new CommentBaseBean();
            bean.setIs_hot(1);
            bean.setTitle(true);
            bean.setPn(pn);
            commentBaseBeans.add(bean);
            commentBaseBeans.addAll(hotComment);
        }

        selfComment = commentBeans.getSelf_comment();
        List<CommentBaseBean> generalComment = commentBeans.getGeneral_comment();
        if (selfComment != null && pn == 1) {
            CommentBaseBean bean = new CommentBaseBean();
            bean.setIs_hot(2);
            bean.setTitle(true);
            bean.setPn(pn);
            commentBaseBeans.add(bean);
            selfComment.setPn(pn);
            commentBaseBeans.add(selfComment);
        }

        if (generalComment != null && generalComment.size() > 0) {
            if (pn == 1 && selfComment == null) {
                CommentBaseBean bean = new CommentBaseBean();
                bean.setIs_hot(2);
                bean.setTitle(true);
                bean.setPn(pn);
                commentBaseBeans.add(bean);
            }
            for (int i=0;i<generalComment.size();i++) {
                CommentBaseBean temp = generalComment.get(i);
                temp.setPn(pn);
                commentBaseBeans.add(temp);
            }
        }

        addViewItem(commentBaseBeans);
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (commentBaseBeans.size()<pc) {
            if (pn==1 && commentBaseBeans.size()==0) {
                CommentAllListFragmentAdapter.ViewBean viewBean = new CommentAllListFragmentAdapter.ViewBean(CommentAllListFragmentAdapter.ViewType.EMPTY, null);
                dataSet.add(viewBean);
                mAdapter.notifyDataSetChanged();
            }
            //没有更多
            refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
        } else {
            pn++;
            refreshLayout.finishLoadMore();//将不会再次触发加载更多事件
        }
        mAdapter.notifyDataSetChanged();
    }

    private void addViewItem(List<CommentBaseBean> list) {
        for (int i = 0; null != list && i < list.size(); i++) {
            CommentBaseBean bean = list.get(i);
            if (bean.isTitle()) {
                CommentAllListFragmentAdapter.ViewBean viewBean = new CommentAllListFragmentAdapter.ViewBean(CommentAllListFragmentAdapter.ViewType.TITLE, new CommentAllListFragmentAdapter.ViewBean.Comment(bean));
                dataSet.add(viewBean);
            } else {
                String str = bean.getContent();
                if (str.contains("EM-")){
                    try {
                        str = StringToUnicodeUtil.unicode2String(str);
                        bean.setContent(str);
                    } catch (Exception e) {
                        LogUtils.e("---m---e.getMessage():"+e.getMessage());
                    }
                }
                CommentAllListFragmentAdapter.ViewBean viewBean = new CommentAllListFragmentAdapter.ViewBean(CommentAllListFragmentAdapter.ViewType.COMMENT, new CommentAllListFragmentAdapter.ViewBean.Comment(bean));
                dataSet.add(viewBean);
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    private void getCommentToken(final CommentBaseBean bean, final int position, final int type, final int i) {
        GetCommentTokenRequest tempRequest = retrofitManager.getCommentTokenRequest();
        api.getCommentToken(tempRequest).enqueue(new MyCallback<ResponseBase<GetCommentTokenResponse>>() {
            @Override
            public void onSuccess(ResponseBase<GetCommentTokenResponse> model) {
                GetCommentTokenResponse data = model.getData_info();
                String token = AESUtils.encrypt4Comment(data.getToken() + "|" + data.getTimes());
                comentToken = token;
                PreferenceUtil.savePreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN, token);
                PreferenceUtil.saveLongPreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN_TIME, data.getTimes());
                if (i==1)
                    onPraise(bean, position, type);
                else if (i==2)
                    onUnPraise(bean, position, type);
                else if (i==3)
                    getData();
            }

            @Override
            public void onFailure(int code, String msg) {
                PreferenceUtil.savePreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN, "-1");
                showToast(msg);
            }
        });
    }

    @Override
    public void onPraise(final CommentBaseBean bean, final int position, final int type) {
        if (NetWorkUtils.isNetworkConnected(mContext)) {
            comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
            if (StringUtils.isEmpty(comentToken) || comentToken.equals("-1")) {
                getCommentToken(bean, position, type, 1);
                return;
            }
            uId = AccountUtil.getInstance().getUid();
            uToken = AccountUtil.getInstance().getToken();
            commentId = bean.getId();

            AddPraiseRequest tempRequest = retrofitManager.addPraiseRequest(comentToken, gameId, uId, uToken, commentId, type, pn);
            api.addPraise(tempRequest).enqueue(new MyCallback<ResponseBase<AddPraiseResponse>>() {
                @Override
                public void onSuccess(ResponseBase<AddPraiseResponse> model) {
                    checkReset(position, 1);
                }

                @Override
                public void onFailure(int code, String msg) {
                    if (code==801)
                        getCommentToken(bean, position, type, 1);
                    resultShow(msg, true, position, 1);
                }
            });
        } else {
            resultShow("网络连接失败，再试试吧~", true, position, 1);
        }
    }

    @Override
    public void onUnPraise(final CommentBaseBean bean, final int position, final int type) {
        if (NetWorkUtils.isNetworkConnected(mContext)) {
            comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
            if (StringUtils.isEmpty(comentToken) || comentToken.equals("-1")) {
                getCommentToken(bean, position, type, 2);
                return;
            }
            uId = AccountUtil.getInstance().getUid();
            uToken = AccountUtil.getInstance().getToken();
            commentId = bean.getId();

            AddPraiseRequest tempRequest = retrofitManager.unPraiseRequest(comentToken, gameId, uId, uToken, commentId, type, pn);
            api.subPraise(tempRequest).enqueue(new MyCallback<ResponseBase<AddPraiseResponse>>() {
                @Override
                public void onSuccess(ResponseBase<AddPraiseResponse> model) {
                    checkReset(position, 2);
                }

                @Override
                public void onFailure(int code, String msg) {
                    if (code==801)
                        getCommentToken(bean, position, type, 2);
                    resultShow(msg, true, position, 2);
                }
            });
        } else {
            resultShow("网络连接失败，再试试吧~", true, position, 2);
        }
    }

    @Override
    public void onRootView(CommentBaseBean bean, int position) {
        this.position = position;
        positionCommentId = bean.getId();
        Intent intent = new Intent(mContext, CommentDetailActivity.class);
        intent.putExtra("commentId", bean.getId());
        intent.putExtra("data", bean);
        startActivity(intent);
    }

    @Override
    public void onClickHead() {

    }

    public void checkReset(int position, int i) {
        if (i==1) {
            mAdapter.resetDespise(position, 1);
        } else {
            mAdapter.resetPraise(position, 1);
        }
//        commentAllList.notifyMoreFinish(true);
    }

    private void resultShow(String msg, boolean b, int position, int type) {
        showToast(msg);
        if (b) {
            if (type==1)
                mAdapter.resetPraise(position, 0);
            else
                mAdapter.resetDespise(position, 0);
        }
    }

    private int position;
    private String positionCommentId;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DeleteOrModifyCommentEvent event) {
        int page = 0;
        if ((position+1)<=pc) {
            page = 1;
        } else {
            if ((position+1)%pc==0) {
                page = (position+1)/pc;
            } else {
                page = ((position+1)/pc) + 1;
            }
        }
        getDataByPn(page);
    }

    private void getDataByPn(int pn) {
        comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
        if (StringUtils.isEmpty(comentToken) || comentToken.equals("-1")) {
            getCommentToken(null, 0, 0, 3);
            return;
        }
        uId = AccountUtil.getInstance().getUid();
        uToken = AccountUtil.getInstance().getToken();

        GetGameCommentRequest commentRequest = retrofitManager.getGameCommentsRequest(comentToken, gameId, uId, pn, pc);
        api.getGameComments(commentRequest).enqueue(new MyCallback<ResponseBase<CommentAllListResponse>>() {
            @Override
            public void onSuccess(ResponseBase<CommentAllListResponse> model) {
                List<CommentBaseBean> allList = new ArrayList<>();

                if (model.getData_info().getSelf_comment()!=null)
                    allList.add(model.getData_info().getSelf_comment());
                if (model.getData_info().getHot_comment()!=null && model.getData_info().getHot_comment().size()>0)
                    allList.addAll(model.getData_info().getHot_comment());
                if (model.getData_info().getGeneral_comment()!=null && model.getData_info().getGeneral_comment().size()>0)
                    allList.addAll(model.getData_info().getGeneral_comment());

                try{
                    for (int i=0;i<allList.size();i++) {
                        if (positionCommentId.equals(allList.get(i).getId())){
                            String str = allList.get(i).getContent();
                            if (str.contains("EM-")){
                                try {
                                    str = StringToUnicodeUtil.unicode2String(str);
                                    allList.get(i).setContent(str);
                                } catch (Exception e) {
                                    LogUtils.e("---m---e.getMessage():"+e.getMessage());
                                }
                            }
                            CommentAllListFragmentAdapter.ViewBean viewBean = new CommentAllListFragmentAdapter.ViewBean(CommentAllListFragmentAdapter.ViewType.COMMENT, new CommentAllListFragmentAdapter.ViewBean.Comment(allList.get(i)));
                            dataSet.set(position, viewBean);
                            mAdapter.notifyItemChanged(position);
                        }
                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }
}
